<template>
    <el-dialog v-model="showDialog" :style = "myStyle" :before-close="handleClose">
        <el-form ref="loginForm" :rules="rules" :model="user">
            <el-form-item >
                <h1 style="width:100%;text-align: center;">用户{{type == 'login'?'登录':'注册'}}</h1>
            </el-form-item>
            <el-form-item prop="customerName" >
                <el-input  :prefix-icon="User"  @blur="checkCustomerName" placeholder="请输入用户名" class="loginItem" style="height:40px" v-model="user.customerName" />
            </el-form-item>
            <el-form-item prop="nickName" v-if="type == 'logon'">
                <el-input  :prefix-icon="User" placeholder="请输入昵称" class="loginItem" style="height:40px" v-model="user.nickName" />
            </el-form-item>
            <el-form-item prop="password">
                <el-input :prefix-icon="Key" placeholder="请输入密码" class="loginItem" style="height:40px" show-password  v-model="user.password" />
            </el-form-item>
            <el-form-item prop="repassword" v-if="type == 'logon'">
                <el-input :prefix-icon="Key" @blur="checkPassword" placeholder="请再次输入密码" class="loginItem" style="height:40px" show-password  v-model="user.repassword" />
            </el-form-item>
            <el-form-item prop="telephone" v-if="type == 'logon'">
                <el-input :prefix-icon="Iphone" placeholder="请输入手机号" @blur="checkTelephone" class="loginItem" style="width: 58%;height:40px"  v-model="user.telephone" />
                <el-button style="width: 40%;margin-left: 2%;" type="primary" class="loginItem" plain  @click="getVerifyCode">获取验证码{{countDown}}</el-button>
            </el-form-item>
            <el-form-item prop="verifyCode" v-if="type == 'logon'">
                <el-input :prefix-icon="Message"  placeholder="请输入验证码" class="loginItem" style="height:40px" v-model="user.verifyCode" />
            </el-form-item>
            <el-form-item>
                <el-button style="width: 100%;height:40px" v-if="type == 'login'" class="loginItem" type="primary"  @click="login">登录</el-button>
                <el-button style="width: 100%;height:40px" v-if="type == 'logon'" class="loginItem" type="primary"  @click="logon">注册</el-button>
            </el-form-item>
            <el-form-item>
                <el-button-group style="width: 100%;height:20px">
                <el-button style="width: 50%;" class="loginItem" plain  @click="toLogin">登录</el-button>
                <el-button style="width: 50%;" class="loginItem" plain  @click="toLogon">注册</el-button>
                </el-button-group>
            </el-form-item>
        </el-form>
    </el-dialog>
</template>

<script setup>
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'
    import {reactive, ref,onMounted } from 'vue'
    import router from '@/router'
    import {User, Key, Iphone,Message } from '@element-plus/icons-vue'
    let showDialog = ref(false)
    let loginStyle = "width:350px;height: 350px;border-radius: 10px"
    let logonStyle = "width:350px;height: 560px;border-radius: 10px"
    let myStyle = ref("")
    let countDown = ref("")
    let emits = defineEmits(["afterLogin"])
    let type = ref("login")
    let verifyCodeInterval = null
    let customerNameUseful = ref(false)
    let mobileUseful = ref(false)
    let passwordUseful = ref(false)
    const loginForm = ref();
    const rules = reactive({
        customerName: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        nickName: [
            { required: true, message: '请输入昵称', trigger: 'blur' },
        ],
        password: [
            { required: true,message: '请输入密码', trigger: 'blur',},
        ],
        repassword: [
            { required: true,message: '请再次输入密码', trigger: 'blur',},
        ],
        telephone: [
            { required: true,message: '请再次输入手机号', trigger: 'blur',},
        ],
        verifyCode: [
            { required: true,message: '请输入验证码', trigger: 'blur',},
        ],
    })
    onMounted(()=>{
        myStyle.value = loginStyle
        type.value = "login"
    })
    // const router = useRouter()
    const user = reactive({
        // customerName: 'zhangsan',
        // password: '111111'
    })
    function login() {
        loginForm.value.validate((valid, fields)=>{
            if(valid){
                request.post("/api/client/login", user).then(resp => {
                    ElMessage({message: '登录成功！',type: 'success'})
                    showDialog.value = false
                    emits("afterLogin", resp)
                });
            }else{
                ElMessage({message: '缺少必填项！',type: 'error'})
            }
        })
    }

    function logon() {
        loginForm.value.validate((valid, fields) => {
            if(!mobileUseful.value || !customerNameUseful.value || !passwordUseful.value){
                ElMessage({message: '请检查用户名,手机号,密码',type: 'error'})
                return
            }
            if(valid){
                request.post("/api/client/logon", user).then(resp => {
                    ElMessage({message: '注册成功！',type: 'success'})
                    showDialog.value = false
                    emits("afterLogin", resp)
                });
            }else{
                ElMessage({message: '缺少必填项,或用户名手机号重复',type: 'error'})
            }
        })
    }

    function checkCustomerName() {
        if(type.value != 'logon'){
            return
        }
        if(!user.customerName){
            ElMessage({message: '请输入用户名！',type: 'error'})
            return
        }
        request.get(`/api/client/checkCustomerName/${user.customerName}`).then(resp => {
            if(!resp){
                ElMessage({message: '用户名重复！',type: 'error'})
                customerNameUseful.value = false
            }else{
                customerNameUseful.value = true
            }
        });
    }

    function checkTelephone() {
        if(!user.telephone){
            ElMessage({message: '请输入手机号！',type: 'error'})
            return
        }
        request.get(`/api/client/checkTelephone/${user.telephone}`).then(resp => {
            if(!resp){
                ElMessage({message: '用户名手机已被注册！',type: 'error'})
                mobileUseful.value = false
            }else{
                mobileUseful.value = true
            }
        });
    }

    function checkPassword() {
        if(user.password != user.repassword ){
            passwordUseful.value = false
            ElMessage({message: '两次输入密码不一致！',type: 'error'})
        }else{
            passwordUseful.value = true
        }
    }

    function toLogin(){
        myStyle.value = loginStyle
        type.value = "login"
        loginForm.value.resetFields()//重置表单校验
    }

    function toLogon(){
        myStyle.value = logonStyle
        type.value = "logon"
        loginForm.value.resetFields()//重置表单校验
    }

    function getVerifyCode(){
        if(mobileUseful.value){
            if(countDown.value == ''||countDown.value == '0'){
                let count = 60
                verifyCodeInterval = window.setInterval(function(){
                    count--
                    countDown.value = count
                    if(count == 0){
                        countDown.value = ""
                        window.clearInterval(verifyCodeInterval)
                    }
                },1000)
                request.get(`/api/client/getVerifyCode/${user.telephone}`).then(resp => {
                    ElMessage({message: `验证码${resp}`,type: 'success'})
                    console.log(`验证码${resp}`)
                });
            }else{
                ElMessage.error("不可重复获取验证码")
            }
        }else{
            if(user.telephone){
                ElMessage.error("手机号重复")
            }else{
                ElMessage.error("请输入手机号")
            }
        }
    }

    function handleClose(){
        ElMessage({message:"未登录",type:"error",duration:1000} )
        showDialog.value = false
    }
    defineExpose({showDialog})
</script>
<style scoped>
    .loginItem{
        height:35px;
        font-size: 16px;
    }
</style>